package com.tbl.modules.wms.controller.instorage;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.tbl.common.utils.IPUtils;
import com.tbl.common.utils.PageTbl;
import com.tbl.common.utils.PageUtils;
import com.tbl.common.utils.StringUtils;
import com.tbl.modules.platform.constant.MenuConstant;
import com.tbl.modules.platform.controller.AbstractController;
import com.tbl.modules.platform.service.system.RoleService;
import com.tbl.modules.wms.constant.Constant;
import com.tbl.modules.wms.entity.instorage.InstorageDetail;
import com.tbl.modules.wms.entity.split.RfidBind;
import com.tbl.modules.wms.entity.storageinfo.StorageInfo;
import com.tbl.modules.wms.service.instorage.InstorageDetailService;
import com.tbl.modules.wms.service.instorage.InstorageService;
import com.tbl.modules.wms.service.inventory.RfidBindService;
import com.tbl.modules.wms.service.storageinfo.StorageInfoService;
import com.tbl.modules.wms.service.webservice.client.WmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 入库管理--桌面写卡器
 * @author 70486
 */
@Controller
@RequestMapping(value = "/desktopWriter")
public class DesktopWriterController extends AbstractController {

    /**
     * 入库管理-入库表
     */
    @Autowired
    private InstorageService instorageService;
    /**
     * 角色信息
     */
    @Autowired
    private RoleService roleService;
    /**
     * wms调用接口入口
     */
    @Autowired
    private WmsService wmsService;
    /**
     * 入库明细
     */
    @Autowired
    private InstorageDetailService instorageDetailService;
    /**
     * 库存查询
     */
    @Autowired
    private StorageInfoService storageInfoService;
    /**
     * rfid绑定
     */
    @Autowired
    private RfidBindService rfidBindService;

    /**
     * 跳转到rfid绑定列表页面
     * @return ModelAndView
     */
    @RequestMapping(value = "/toList")
    public ModelAndView toList() {
        ModelAndView mv = this.getModelAndView();
        mv.addObject("operationCode", roleService.selectOperationByRoleId(getSessionUser().getRoleId(), MenuConstant.desktopWriter));
        mv.setViewName("techbloom/instorage/storagein/desktopWriter_list");
        return mv;
    }

    /**
     * 获取可绑定rfid列表数据
     * @param queryJsonString 查询条件
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/list.do")
    @ResponseBody
    public Map<String, Object> list(String queryJsonString) {
        Map<String, Object> map = new HashMap<>(4);
        if (!StringUtils.isEmptyString(queryJsonString)) {
            map = JSON.parseObject(queryJsonString);
        }
        //okk
        map.put("org", Arrays.asList(getSessionUser().getFactoryCode().split(",")));
        PageTbl page = this.getPage();
        PageUtils utils = instorageService.getPagePackageList(page, map);
        page.setTotalRows(utils.getTotalCount() == 0 ? 1 : utils.getTotalCount());
        //初始化分页对象
        executePageMap(map, page);
        map.put("rows", utils.getList());
        map.put("total", utils.getTotalPage() == 0 ? 1 : utils.getTotalPage());
        return map;
    }

    /**
     * 获取本地ip地址
     * @param request 请求
     * @return String ip地址
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("X-Real-IP");
        if (ip!= null && !"".equals(ip) && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }
        ip = request.getHeader("X-Forwarded-For");
        if (ip!= null && !"".equals(ip)  && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个IP值，第一个为真实IP。
            int index = ip.indexOf(',');
            if (index != -1) {
                return ip.substring(0, index);
            }else {
                return ip;
            }
        } else {
            return request.getRemoteAddr();
        }
    }
    
    
    /**
     * 桌面写卡器rfid绑定
     * @param rfid
     * @return ModelAndView
     */
    @RequestMapping(value = "/deskRfidBind.do")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public Map<String,Object> deskRfidBind(String rfid) {
    	rfid = new DecimalFormat("000000000000").format(Long.valueOf(rfid));
    	Map<String,Object> map = new HashMap<>(1);
    	Map<String,Object> xmlParam = new HashMap<>(1);
    	String epc;
    	try {
    		RfidBind rfidBind = rfidBindService.selectOne(new EntityWrapper<RfidBind>().eq("RFID", rfid));
    		if(rfidBind==null) {
    			HashMap<String, Object> param = new HashMap<>(1);
    			param.put("RFID", rfid);
    			InstorageDetail instorageDetail = instorageDetailService.selectByMap(param).get(0);
    			if(instorageDetail==null) {
    				return new HashMap<String,Object>(2){{
        				put("result",false);
        				put("msg","绑定失败！");
        			}};
    			}else {
    				epc = instorageDetail.getRfid();
    			}
    		}else {
    			epc = rfidBind.getRfid();
    			rfidBind.setType(Constant.STRING_ONE);
        		rfidBindService.updateById(rfidBind);
    		}
    		String content = IPUtils.getIpAddr(request);
    		if("0:0:0:0:0:0:0:1".equals(content)){
    			content = "localhost";
            }
    		if(StringUtils.isNotEmpty(content)) {
    			xmlParam.put("content", content);
    			xmlParam.put("epc",epc);
    			wmsService.RFIDWRITE(xmlParam);
    		}else {
    			return new HashMap<String,Object>(2){{
    				put("result",false);
    				put("msg","绑定失败！");
    			}};
    		}
    		
    		StorageInfo storageinfo = storageInfoService.selectOne(new EntityWrapper<StorageInfo>().eq("RFID", rfid));
    		if(storageinfo!=null) {
    			storageinfo.setState(Constant.INT_ONE);
    			storageInfoService.updateById(storageinfo);
    		}
    		
    		map.put("result", true);
    		map.put("msg", "绑定成功！");
		} catch (Exception e) {
			e.printStackTrace();
			return new HashMap<String,Object>(2){{
				put("result",false);
				put("msg","绑定失败！");
			}};
		}
        return map;
    }

}
